package com.zklh.book.system.service.impl;

import com.zklh.book.system.model.User;
import com.zklh.book.system.repo.UserRepo;
import com.zklh.book.system.repo.impl.UserRepoImpl;
import com.zklh.book.system.service.UserService;
import com.zklh.book.system.util.TokenGenerator;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户服务实现
 *
 * @author 坐看落花
 * @version 1.0
 * @date 2021/3/20 19:33
 */
public class UserServiceImpl implements UserService {

    private Map<String, User> tokenMap = new HashMap<>();
    private UserRepo userRepo = new UserRepoImpl();

    @Override
    public User get(String account) {
        return userRepo.get(account);
    }

    @Override
    public String login(String account, String password) {

        User user = userRepo.get(account);

        if (user != null && user.getPassword().equals(password)) {
            String token = TokenGenerator.next();
            tokenMap.put(token, user);
            return token;
        }

        return null;
    }

    @Override
    public void logout(String token) {
        tokenMap.remove(token);
    }

    @Override
    public boolean logined(String token) {
       return tokenMap.containsKey(token);
    }

    @Override
    public User getByToken(String token) {
        return tokenMap.get(token);
    }
}
